package com.antler.smt.utils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * AES加密和解密
 * @author wangyanhui
 *
 */
public class AESUtil {

    /**
     * AES加密
     * @param plaintext 明文
     * @param key
     * @return 密文
     */
    public static String encryptString(final String plaintext, final String key) {

        return parseByte2HexStr(encrypt(plaintext, key));
    }

    /**
     * AES解密
     * @param ciphertext 密文
     * @param key
     * @return 明文
     */
    public static String decryptString(final String ciphertext, final String key) {

        final byte[] decryptFrom = parseHexStr2Byte(ciphertext);
        final byte[] decryptResult = decrypt(decryptFrom, key);
        return new String(decryptResult);
    }

    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @param key 加密密码
     * @return
     */
    private static byte[] encrypt(final String content, final String key) {

        try {
            final KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new java.security.SecureRandom(key.getBytes()));
            final SecretKey secretKey = kgen.generateKey();
            final byte[] enCodeFormat = secretKey.getEncoded();
            final SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            // 创建密码器
            final Cipher cipher = Cipher.getInstance("AES");
            final byte[] byteContent = content.getBytes("UTF-8");
            // 初始化
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            final byte[] result = cipher.doFinal(byteContent);
            // 加密
            return result;
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (final NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (final InvalidKeyException e) {
            e.printStackTrace();
        } catch (final UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (final IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (final BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * @param content 待解密内容
     * @param key 解密密钥
     * @return
     */
    private static byte[] decrypt(final byte[] content, final String key) {

        try {
            final KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new java.security.SecureRandom(key.getBytes()));
            final SecretKey secretKey = kgen.generateKey();
            final byte[] enCodeFormat = secretKey.getEncoded();
            final SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            // 创建密码器
            final Cipher cipher = Cipher.getInstance("AES");
            // 初始化
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            final byte[] result = cipher.doFinal(content);
            // 加密
            return result;
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (final NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (final InvalidKeyException e) {
            e.printStackTrace();
        } catch (final IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (final BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将16进制转换为二进制
     * @param hexStr
     * @return
     */
    private static byte[] parseHexStr2Byte(final String hexStr) {

        if (hexStr.length() < 1) {
            return null;
        }
        final byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            final int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            final int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 将二进制转换成16进制
     * @param buf
     * @return
     */
    private static String parseByte2HexStr(final byte buf[]) {

        final StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
}
